<?php

namespace Admin\Models\app;

use Admin\Models\BaseModel;
use Admin\Models\sys\XhsysEnum;
use Helpers\Main;

class XhappRetain extends BaseModel
{

    /**
     *
     * @var integer
     */
    public $iARId;

    /**
     *
     * @var string
     */
    public $sTabletItemNo;

    /**
     *
     * @var string
     */
    public $sAppName;

    /**
     *
     * @var string
     */
    public $sAppPackage;

    /**
     *
     * @var string
     */
    public $sAppVersion;

    /**
     *
     * @var integer
     */
    public $iRetainType;

    /**
     *
     * @var integer
     */
    public $bDisable;

    /**
     *
     * @var integer
     */
    public $bDelete;

    /**
     *
     * @var string
     */
    public $tCreateDate;

    /**
     *
     * @var string
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     */
    public $tLastModifyDate;

    /**
     *
     * @var string
     */
    public $iLastModifyUserId;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
        $this->setSource("XHApp_Retain");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHApp_Retain';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhappRetain[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhappRetain
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 根据平板型号及文件提取出的数组导入到保留列表中，并返回插入条数或失败
     *
     * @param $tabletItemNo
     * @param $appArr
     * @return bool
     *
     * create by ck 20161018
     */
    public static function importRetainList($tabletItemNo, $appArr)
    {
        $userId = Main::getLoginUserInfo('userId');
        $nowTime = date('Y-m-d H:i:s');

        //查找该平板下已存在包名
        $existPackage = self::find([
            'columns'       => 'sAppPackage',
            'conditions'    => 'bDelete = 0 AND sTabletItemNo = :sTabletItemNo:',
            'bind'          => [
                'sTabletItemNo' => $tabletItemNo,
            ]
        ])->toArray();
        $existPackage = array_column($existPackage, 'sAppPackage');

        //批量插入，已存在则跳过
        $insertSql = 'INSERT INTO XHApp_Retain (sTabletItemNo,sAppName,sAppPackage,sAppVersion,iRetainType,bDisable,bDelete,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId) VALUES ';
        $valueArr = array();
        $count['file'] = $count['company'] = 0;
        foreach($appArr as $app){
            if(in_array($app['package'], $existPackage)) continue;
            $valueArr[] = "('{$tabletItemNo}','{$app['appName']}','{$app['package']}','{$app['version']}',3,0,0,'{$nowTime}',{$userId},'{$nowTime}',{$userId})";
            $count['file']++;
        }

        //查找公司及外部应用
        $companyApp = XhappStore::getInfoForRetain();
        foreach($companyApp as $app){
            if(in_array($app['sAppPackage'], $existPackage)) continue;
            $valueArr[] = "('{$tabletItemNo}','{$app['sAppName']}','{$app['sAppPackage']}','{$app['sAppVersion']}','{$app['iAppType']}',0,0,'{$nowTime}',{$userId},'{$nowTime}',{$userId})";
            $count['company']++;
        }

        //返回插入数量数组
        if(!$valueArr) return $count;
        $insertSql .= implode(',', $valueArr);
        if(!\Phalcon\Di::getDefault()->get('db')->execute($insertSql)) return false;
        return $count;
    }

    /**
     * 新增应用时添加各平板的保留应用记录
     *
     * @param $packageName
     * @param null $appName
     * @param null $version
     * @param int $type
     * @return bool
     *
     * create by ck 20161018
     */
    public static function createRecordForNewApp($packageName, $appName = null, $version = null, $type = 1)
    {
        $userId = Main::getLoginUserInfo('userId');
        $nowTime = date('Y-m-d H:i:s');
        $tabletList = XhsysEnum::getEnumByNodeName('平板列表');
        $tabletList = array_values($tabletList);
        if(!$tabletList) return true;

        //查找该包名下已存在平板
        $existTablet = self::find([
            'columns'       => 'sTabletItemNo',
            'conditions'    => "bDelete = 0 AND sAppPackage = :sAppPackage: AND sTabletItemNo IN ({tabletItem:array})",
            'bind'          => [
                'sAppPackage'   => $packageName,
                'tabletItem'    => $tabletList
            ]
        ])->toArray();
        $existTablet = array_column($existTablet, 'sTabletItemNo');

        //批量插入，已存在则跳过
        $insertSql = 'INSERT INTO XHApp_Retain (sTabletItemNo,sAppName,sAppPackage,sAppVersion,iRetainType,bDisable,bDelete,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId) VALUES ';
        $valueArr = array();
        foreach($tabletList as $tablet){
            if(in_array($tablet, $existTablet)) continue;
            $valueArr[] = "('{$tablet}','{$appName}','{$packageName}','{$version}',{$type},0,0,'{$nowTime}',{$userId},'{$nowTime}',{$userId})";
        }

        //无数据则返回true，否则返回执行结果
        if(!$valueArr) return true;
        $insertSql .= implode(',', $valueArr);
        return \Phalcon\Di::getDefault()->get('db')->execute($insertSql);
    }

    /**
     * 根据应用包名删除保留应用记录
     *
     * @param $appPackArr
     * @return mixed
     *
     * create by ck 20161019
     */
    public static function deleteRecordByAppPackage($appPackArr)
    {
        //查找应用名称数组下未删除的信息
        $existAppPack = XhappStore::find([
            'columns'    => 'sAppPackage',
            'conditions' => 'bDelete = 0 AND bAppHistory = 0 AND sAppPackage IN ({packArr:array})',
            'bind'       => [
                'packArr'   => $appPackArr
            ]
        ])->toArray();
        $existAppPack = array_column($existAppPack, 'sAppPackage');

        //求差集并删除，如无差集则直接返回true
        $appPackArr = array_diff($appPackArr, $existAppPack);
        if(!$appPackArr) return true;
        return self::find([
            'conditions'    => 'bDelete = 0 AND sAppPackage IN ({nameArr:array})',
            'bind'          => [
                'nameArr'       => $appPackArr
            ]
        ])->delete();
    }
}
